class SanPham
  include MongoMapper::Document
  
  before_save :xac_dinh_mac_dinh

  key     :slug,              String,   :presence => true,    :length => {:minimum => 4}, :uniqueness => true
  key     :hinh_anh,          String,   :presence => true,    :length => {:minimum => 10}
  key     :dang_kich_hoat,    Boolean
  key     :gia,               Integer,  :presence => true
  key     :gia_khuyen_mai,    Integer
  key     :khuyen_mai_bat_dau,Time
  key     :khuyen_mai_ket_thuc,Time   
  timestamps!

  belongs_to  :danh_muc
  belongs_to  :nguoi_dung
  many :noi_dung_san_phams
  
  
  validates :gia, :numericality => { :only_integer => true, :greater_than => 1000 }
  validates :gia_khuyen_mai, :numericality => { :only_integer => true, :greater_than => 1000 }, :allow_nil => true
  
  def xac_dinh_mac_dinh
    if self.dang_kich_hoat.nil?
    self.dang_kich_hoat = true;
    end
  end
  
  def noi_dung(ngon_ngu, bat_ky = false)
    ket_qua = nil
    for noi_dung_sp in self.noi_dung_san_phams
      if noi_dung_sp.ngon_ngu == ngon_ngu
        ket_qua = noi_dung_sp
      end
    end
    if ket_qua.nil? && bat_ky
      ket_qua = self.noi_dung_san_phams[0]
    end
    return ket_qua
  end
  
  def co_khuyen_mai(hom_nay)
    if !self.gia_khuyen_mai.present?
      return false
    end
    if !(self.khuyen_mai_bat_dau.present? && self.khuyen_mai_ket_thuc.present?)
      return false;
    end
    if !(self.khuyen_mai_bat_dau .. (self.khuyen_mai_ket_thuc + 24*3600)).cover?(hom_nay)
      return false;
    end
    return true
  end

  
  
end

class NoiDungSanPham
  include MongoMapper::EmbeddedDocument
  
  before_save :xac_dinh_mac_dinh
  
  key     :tieu_de,           String,   :presence => true,    :length => {:minimum => 4}
  key     :noi_dung,          String
  key     :meta_description,   String
  key     :dang_kich_hoat,    Boolean
 
  belongs_to  :nguoi_dung
  
  def xac_dinh_mac_dinh
    if self.dang_kich_hoat.nil?
    self.dang_kich_hoat = true;
    end
  end
end

